<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomAction from './components/RoomAction.vue'
import RoomMessage from './components/RoomMessage.vue'
import { io } from 'socket.io-client'
import type { Socket } from 'socket.io-client'
import { onMounted, onUnmounted } from 'vue'
import { baseURL } from '@/utils/request'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'
import type { TimeMessages, Message } from '@/types/room'
import { MsgType, OrderType } from '@/enums'
import { ref, nextTick } from 'vue'

import type { ConsultOrderItem, Image } from '@/types/consult'
import { getConsultOrderDetail } from '@/services/consult'
import dayjs from 'dayjs'
import { showToast } from 'vant'
import { provide } from 'vue'

const consult = ref<ConsultOrderItem>()
const loadConsult = async () => {
  const res = await getConsultOrderDetail(route.query.orderId as string)
  consult.value = res.data
}

const route = useRoute()
const store = useUserStore()
// 存储消息列表的数据
const list = ref<Message[]>([])
let socket: Socket

// 默认初始化看到最新消息
const initMsg = ref(true)

onMounted(async () => {
  loadConsult()
  socket = io(baseURL, {
    auth: {
      token: `Bearer ${store.user?.token}`
    },
    query: {
      orderId: route.query.orderId
    }
  })

  socket.on('connect', () => {
    // 建立连接成功
    console.log('连接成功')
  })
  socket.on('disconnect', () => {
    // 已经断开连接
    console.log('连接失败')
  })

  socket.on('error', () => {
    // 错误异常消息
    console.log('发送错误')
  })

  // 接收默认消息
  socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
    // 准备转换常规消息列表  把二维数组转换为一维数组
    const arr: Message[] = []
    data.forEach((item, i) => {
      // 记录最早时间
      if (i === 0) time.value = item.createTime
      // 添加时间分组
      arr.push({
        msgType: MsgType.Notify,
        msg: {
          content: item.createTime
        },
        createTime: item.createTime,
        id: item.createTime
      })
      arr.push(...item.items)
    })
    // 向上追加数据，最新的数据在前面的位置
    list.value.unshift(...arr)
    console.log(list.value)

    loading.value = false
    if (!data.length) {
      return showToast('没有聊天记录了')
    }
    // 默认展示最新消息
    if (initMsg.value) {
      // 更新消息状态
      socket.emit('updateMsgStatus', arr[arr.length - 1].id)
      nextTick(() => {
        window.scrollTo(0, document.body.scrollHeight)
        initMsg.value = false
      })
    }
  })

  // 订单状态 在onMounted注册
  socket.on('statusChange', () => loadConsult())

  // 接收消息 在onMounted注册,可以获取到每一条消息
  socket.on('receiveChatMsg', async (event) => {
    console.log(event, 'event')

    list.value.push(event)
    await nextTick()
    // 更新消息状态
    socket.emit('updateMsgStatus', event.id)
    window.scrollTo(0, document.body.scrollHeight)
  })
})
// 发送文字消息
const sendText = (text: string) => {
  // 发送信息需要  发送人  收消息人  消息类型  消息内容
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgText,
    msg: { content: text }
  })
}
// 发送图片消息
const sendImage = (img: Image) => {
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgImage,
    msg: { picture: img }
  })
}

// 下拉刷新状态
const loading = ref(true)
const time = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))
// 下拉刷新回调
const onRefresh = () => {
  socket.emit('getChatMsgList', 20, time.value, consult.value?.id)
}
// 提供问诊订单数据给后代组件
provide('consult', consult)
// 成功后修改消息，暴露给评价组件
const completeEva = (score: number) => {
  const item = list.value.find((item) => item.msgType === MsgType.CardEvaForm)
  if (item) {
    item.msg.evaluateDoc = { score }
    item.msgType = MsgType.CardEva
  }
}
// 提供函数
provide('completeEva', completeEva)

onUnmounted(() => {
  socket.close() // 关闭socket
})
</script>

<template>
  <div class="room-page">
    <cp-nav-bar title="问诊室" />
    <room-status
      :status="consult?.status"
      :countdown="consult?.countdown"
    ></room-status>
    <!-- 开启下拉刷新 -->
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <room-message
        v-for="item in list"
        :key="item.id"
        :item="item"
      ></room-message>
    </van-pull-refresh>

    <room-action
      @send-text="sendText"
      @send-image="sendImage"
      :disabled="consult?.status !== OrderType.ConsultChat"
    ></room-action>
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
